package com.weiyi.mashangzhu.Roomer.Fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMConversation.EMConversationType;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.hyphenate.util.NetUtils;
import com.squareup.okhttp.Request;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.easemob.Constant;
import com.weiyi.mashangzhu.easemob.db.ChatBean;
import com.weiyi.mashangzhu.easemob.db.ChatDao;
import com.weiyi.mashangzhu.easemob.db.InviteMessgeDao;
import com.weiyi.mashangzhu.easemob.ui.ChatActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class Fragment_Message extends EaseConversationListFragment {

    private TextView errorText;

    @Override
    protected void initView() {
        super.initView();
        View errorView = (LinearLayout) View.inflate(getActivity(), R.layout.fragment_message, null);
        errorItemContainer.addView(errorView);
        errorText = (TextView) errorView.findViewById(R.id.tv_connect_errormsg);

        ChatDao chatDao = new ChatDao(getContext());
        List<ChatBean> all = chatDao.findAll();
        Gson gson = new Gson();
        jsonNickAndHead = gson.toJson(all);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    @Override
    protected void setUpView() {
        super.setUpView();
        // register context menu
        registerForContextMenu(conversationListView);
        conversationListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EMConversation conversation = conversationListView.getItem(position);
                String username = conversation.conversationId();
                if (username.equals(EMClient.getInstance().getCurrentUser()))
                    Toast.makeText(getActivity(), R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
                else {
                    initNickAndHead(username);
                    ChatDao chatDao = new ChatDao(getContext());
                    String[] leftAccount = chatDao.findByAccount(username);
                    String rightHead = "";
                    String token = SPUtils.get(getContext(), "token", "") + "";
                    String[] split = token.split("@");
                    if (split.length > 1) {
                        String userAccount = split[1];
                        if (userAccount != null) {
                            String[] rightAccount = chatDao.findByAccount(userAccount);
                            if (rightAccount != null && rightAccount.length > 0) {
                                rightHead = rightAccount[1];
                            }
                        }
                    }

                    // start chat acitivity
                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    if(conversation.isGroup()){
                        if(conversation.getType() == EMConversationType.ChatRoom){
                            // it's group chat
                            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_CHATROOM);
                        }else{
                            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
                        }

                    }
                    // it's single chat
                    intent.putExtra(Constant.EXTRA_USER_ID, username);
                    if (leftAccount != null && leftAccount.length > 0) {
                        intent.putExtra(Constant.LEFT_NICK, leftAccount[0]);
                        intent.putExtra(Constant.LEFT_HEAD, leftAccount[1]);
                    }
                    intent.putExtra(Constant.RIGHT_HEAD, rightHead);
                    startActivity(intent);
                }
            }
        });
        super.setUpView();
        //end of red packet code
    }

    private void initNickAndHead(final String id) {
        OkHttpUtils.get().addParams("id", id).url(API.BaseApi_R + API.findHeadandName).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("status") == 0) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        String uNickname = jsonObject1.getString("uNickname");
                        String uHead = jsonObject1.getString("uHead");
                        saveNickAndAvatar(id, uNickname, uHead);
                    }
                } catch (JSONException e) {

                }
            }
        });
    }

    private void saveNickAndAvatar(String userAccount, String uNickname, String uHead) {
        ChatDao chatDao = new ChatDao(getContext());
        if (!chatDao.isExist(userAccount)) {
            chatDao.add(userAccount, uNickname, uHead);
        } else {
            chatDao.update(userAccount, uNickname, uHead);
        }
    }


    @Override
    protected void onConnectionDisconnected() {
        super.onConnectionDisconnected();
        if (NetUtils.hasNetwork(getActivity())){
            errorText.setText(R.string.can_not_connect_chat_server_connection);
        } else {
            errorText.setText(R.string.the_current_network);
        }
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        getActivity().getMenuInflater().inflate(R.menu.em_delete_message, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
//        boolean deleteMessage = false;
//        if (item.getItemId() == R.id.delete_message) {
//            deleteMessage = true;
//        } else if (item.getItemId() == R.id.delete_conversation) {
//            deleteMessage = false;
//        }
        EMConversation tobeDeleteCons = conversationListView.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
        if (tobeDeleteCons == null) {
            return true;
        }
        if(tobeDeleteCons.getType() == EMConversationType.GroupChat){
            EaseAtMessageHelper.get().removeAtMeGroup(tobeDeleteCons.conversationId());
        }
        try {
            // delete conversation
            EMClient.getInstance().chatManager().deleteConversation(tobeDeleteCons.conversationId(), true);
            InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(getActivity());
            inviteMessgeDao.deleteMessage(tobeDeleteCons.conversationId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        refresh();

        // update unread count
//        ((MainActivity_R) getActivity()).updateUnreadLabel();
        return true;
    }

}

